#include "tools.h"
#include "client_service_view.h"
#include "book_list.h"
#include "signal.h"

char* hide_passwd(char* passwd);
void init(void);
bool login(void);
void enroll(void);
int main()
{
	init();
	ClientServiceView view;
	while(1)
	{
		system("clear");
		cout << "＊＊＊欢迎使用指针图书馆系统＊＊＊" << endl;
		cout << "[1]登录" << endl;
		cout << "[2]注册" << endl;
		cout << "[q]退出" << endl;
		switch(getch())
		{
			case '1' : if(login()) view.menu();break;
			case '2' : enroll();break;
			case 'q' : return 0 ;
		}
	}
}

void enroll(void)
{
	system("clear");
	cout << "新用户注册" << endl;
	string name;
	do
	{
		cout << "昵称:";
		cin >> name;
		getch();
		if(14 < name.size())
		{
			cout << "昵称过长,请重新输入" << endl;
		}
	}while(14 < name.size());
	char passwd[30] = {};
	char passwd1[30] = {};
	do
	{
		cout << "密码:";
		hide_passwd(passwd);
		cout << "请再次输入密码:";
		hide_passwd(passwd1);
		if(14 < strlen(passwd))
		{
			cout << "密码过长,请重新输入" << endl;
		}
		else if(0 != strcmp(passwd,passwd1))
		{
			cout << "密码不一致,请重新输入" << endl;
		}
	 }while(14 < strlen(passwd) || 0 != strcmp(passwd,passwd1) );
	 Account acc;
	 acc.m_name = name;
	 acc.m_passwd = passwd;
	 acc.m_credit = 100;
	 acc.m_money = 0;
	 acc.m_deposit = 0;
	 time_t t;
	 time(&t);
	 struct tm* tp = localtime(&t);
	 acc.m_regTime = *tp;
	 unsigned int id = generator_UserId();
	 acc.m_id = id;
	 
	 AccountData save_acc;
	 save_acc.save(acc);
	 cout << "注册成功,生成账户ID:" << id << "\n"<< endl;
	 get_char();
}

bool login(void)
{
	system("clear");
	cout << "账号ID:";
	unsigned int  id = 0;
	cin >> id;
	getch();
	cout << "密码:" ;
	char passwd[30] = {};
	hide_passwd(passwd);
	AccountData read_acc;
	Account* acc = read_acc.load(id);
	if(acc == NULL)
	{
		cout << "账号不存在\n" << endl;
		get_char();
		return false;
	}
	else if(0 != acc->m_passwd.compare(passwd))
	{
		cout << "密码错误\n" << endl;
		get_char();
		return false;
	}
	else
	{
		CurAccount = *acc;
		delete acc;
		return true;
	}
}

void final(int num)
{
	exit(0);
}

void final_exit(void)
{
	IndexSave();
	AccountData accdata;
	accdata.save(CurAccount);
}

void init(void)
{
	signal(SIGINT,final);
	signal(SIGQUIT,final);
	atexit(final_exit);
	IndexLoad();
}

char* hide_passwd(char* passwd)
{
	char cur_passwd[20] = {};
	int char_num = 0;
	for(int i=0;i<15;i++)
	{
		if( 14 == i)
		{
			printf("\n");
			return NULL;
		}
		cur_passwd[i] = getch();
		
		if( '\n' == cur_passwd[i])
		{
			cur_passwd[i] = 0;
			strcpy(passwd,cur_passwd);
			printf("\n");
			char_num--;
			return passwd;
		}  
		if( 127 == cur_passwd[i] && char_num > 0)  //密码退格
		{
			char_num--;
			cur_passwd[i] = 0;
			--i;
			if( i >= 0 ) 
			{
				cur_passwd[i] = 0;
				--i;
			}
			printf("\b \b");
			continue;
		}
		else if(127 == cur_passwd[i]) 
		{
			cur_passwd[i] = 0;
			--i;
			if( i >= 0 ) 
			{
				cur_passwd[i] = 0;
				--i;
			}
		}
		else 
		{
			char_num++;
			printf("*");
		}
	}
	return passwd;
}

